﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Template10.Services.NavigationService;
using Wasion.HHU.Data.Repositories;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// O modelo do item de página em branco está documentado em http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409

namespace Wasion.HHU.Views
{
    /// <summary>
    /// Uma página vazia que pode ser usada isoladamente ou navegada dentro de um Quadro.
    /// </summary>
    public sealed partial class Login : Page
    {
        UserDbRepository userDb = new UserDbRepository(Shell.conn);

        public Login()
        {
            this.InitializeComponent();
        }

        private async void button_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(textBox.Text.Trim()) || string.IsNullOrEmpty(textBox1.Text.Trim()))
            {
                return;
            }
            var name = textBox.Text.Trim();
            var password = textBox1.Text.Trim();
            var userlist = userDb.GetUsersWithName(name).Result;
            if (userlist.Count <= 0)
            {
                return;
            }
            var user = userlist.First();

            if (user != null && user.PassWord.Equals(Common.Utils.GetMD5(password)))
            {
                Shell.User.Name = name;
                Shell.User.IsLogin = true;

                var userRoles = userDb.GetUserRolesWithLevel(user.Level).Result;
                foreach (var item in userRoles)
                {
                    var list = new ViewModels.UserRole();
                    list.RoleName = item.RoleName;
                    list.AllowRead = item.AllowRead;
                    list.AllowWrite = item.AllowWrite;

                    Shell.User.Roles.Add(list);
                }

                Shell.HamburgerMenu.IsFullScreen = false;
                Shell.HamburgerMenu.NavigationService.Navigate((typeof(Views.HomePage)));
            }
            else
            {
                var msg = new MessageDialog("账号密码不正确");
                await msg.ShowAsync();
            }
        }
    }
}
